How to Export a SQL Query to Excel Using Xbasic

Description

Excel files can be generated with data from Xbasic SQL queries in Alpha Anywhere.

Discussion

SQL queries can be made against a database in Xbasic using a SQL::Connection object to create a SQL::ReultSet. A SQL::ResultSet can be transformed into several different formats - including custom formats using the next() method and assembling the data manually. To transform data into an Excel format, however, you don't need to do it manually. The toExcel() method will generate an Excel file that contains the records from the SQL query.

In the example below, a SQL query is made against the Northwind Access database to get all of the Customer records from the Customers table where the Country field is equal to "Spain". The result of the query is then saved in an Excel file called "Customers_Spain.xls". This example was written to be run in an .a5w page:

<%a5
    dim cn as SQL::Connection
    dim args as SQL::Arguments

    ' Build the SQL statement to execute
    dim sql as c =<<%sql%
SELECT CustomerID, CompanyName, Address, City, Country
FROM Customers
WHERE Country = :COUNTRY
%sql%

    ' Set the argument "COUNTRY" to "Spain"
    args.set("COUNTRY", "Spain")

    ' Open the connection
    if (cn.open("::Name::Northwind_Access") = .f.) then
        ? "Could not open connection. Error was: " + cn.CallResult
        end
    end if

    ' Execute the query
    if (cn.execute(sql, args) = .f.) then
        ? "Error executing SQL query. Error was: " + cn.CallResult
        cn.close()
        end 
    end if

    ' Define file name
    dim filename as c = "C:\path\to\Customers.xls"

    ' Create the Excel File
    if (cn.resultSet.toExcel(filename) = .f.) then 
        ' Something went wrong and the Excel file was not created
        ? "An error occurred. Excel file was not created. Error was: " + cn.resultSet.CallResult
    else
        ' Success!
        ? "Excel file was created"
    end if

    ' Close the connection
    cn.close()
%>

For a more control over the Excel file's creation, the Office Namespace can be used to Generate Excel Spreadsheets.

See Also